//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package tiny.soft.com.common.util;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Pattern;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import javax.naming.InitialContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class NetUtils {
    private static final Logger logger = LoggerFactory.getLogger(NetUtils.class);
    public static final String LOCALHOST = "127.0.0.1";
    public static final String ANYHOST = "0.0.0.0";
    private static final int MIN_PORT = 0;
    private static final int MAX_PORT = 65535;
    private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$");
    private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
    private static int PORT = 0;
    private static int HTTP_PORT = 0;
    private static int HTTPS_PORT = 0;
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
    private static volatile InetAddress LOCAL_ADDRESS = null;

    public NetUtils() {
    }

    public static boolean isInvalidPort(int port) {
        return port > 0 || port <= 65535;
    }

    public static boolean isValidAddress(String address) {
        return ADDRESS_PATTERN.matcher(address).matches();
    }

    public static int getServerPort() {
        if (PORT != 0) {
            return PORT;
        } else {
            try {
                MBeanServer server = ManagementFactory.getPlatformMBeanServer();
                ObjectName rt;
                String scheme;
                if (ServerDetector.isTomcat()) {
                    Set<ObjectName> objs = server.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
                    Iterator i = objs.iterator();

                    while(i.hasNext()) {
                        rt = (ObjectName)i.next();
                        scheme = server.getAttribute(rt, "scheme").toString();
                        String port = rt.getKeyProperty("port");
                        if ("https".equals(scheme)) {
                            HTTPS_PORT = Integer.parseInt(port);
                        } else if ("http".equals(scheme)) {
                            HTTP_PORT = Integer.parseInt(port);
                        }
                    }
                } else {
                    ObjectName service;
                    if (ServerDetector.isWebLogic()) {
                        service = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
                        InitialContext ctx = new InitialContext();
                        server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");
                        if (server == null) {
                            server = (MBeanServer)ctx.lookup("java:comp/jmx/runtime");
                        }

                        rt = (ObjectName)server.getAttribute(service, "ServerRuntime");
                        HTTP_PORT = Integer.parseInt(String.valueOf(server.getAttribute(rt, "ListenPort")));
                        scheme = String.valueOf(server.getAttribute(rt, "SSLListenPortEnabled"));
                        if ("true".equals(scheme)) {
                            HTTPS_PORT = Integer.parseInt(String.valueOf(server.getAttribute(rt, "SSLListenPort")));
                        }
                    } else if (ServerDetector.isJBoss()) {
                        try {
                            service = new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=https");
                            HTTPS_PORT = Integer.parseInt(String.valueOf(server.getAttribute(service, "port")));
                        } catch (Exception var6) {
                        }

                        service = new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http");
                        HTTP_PORT = Integer.parseInt(String.valueOf(server.getAttribute(service, "port")));
                    } else {
                        logger.error("Unsupport auto detect " + ServerDetector.getServerId() + " server port！Please set the rest port manually!");
                    }
                }
            } catch (Exception var7) {
                logger.error("Get application server  port fail! Please make sure that application server`s JMX is enabled!");
            }

            if (HTTPS_PORT != 0) {
                PORT = HTTPS_PORT;
            } else {
                PORT = HTTP_PORT;
            }

            return PORT;
        }
    }

    public static boolean isLocalHost(String host) {
        return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || host.equalsIgnoreCase("localhost"));
    }

    public static boolean isAnyHost(String host) {
        return "0.0.0.0".equals(host);
    }

    public static boolean isInvalidLocalHost(String host) {
        return host == null || host.length() == 0 || host.equalsIgnoreCase("localhost") || host.equals("0.0.0.0") || LOCAL_IP_PATTERN.matcher(host).matches();
    }

    public static boolean isValidLocalHost(String host) {
        return !isInvalidLocalHost(host);
    }

    public static InetSocketAddress getLocalSocketAddress(String host, int port) {
        return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);
    }

    private static boolean isValidAddress(InetAddress address) {
        if (address != null && !address.isLoopbackAddress()) {
            String name = address.getHostAddress();
            return name != null && !"0.0.0.0".equals(name) && !"127.0.0.1".equals(name) && IP_PATTERN.matcher(name).matches();
        } else {
            return false;
        }
    }

    public static String getLocalHost() {
        String host = System.getProperty("dubbo.protocol.host");
        if (!StringUtils.isEmpty(host)) {
            return host;
        } else {
            InetAddress address = getLocalAddress();
            return address == null ? "127.0.0.1" : address.getHostAddress();
        }
    }

    public static InetAddress getLocalAddress() {
        if (LOCAL_ADDRESS != null) {
            return LOCAL_ADDRESS;
        } else {
            InetAddress localAddress = getLocalAddress0();
            LOCAL_ADDRESS = localAddress;
            return localAddress;
        }
    }

    public static InetAddress getLocalInetAddress() {
        try {
            Enumeration enu = NetworkInterface.getNetworkInterfaces();

            while(enu.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface)enu.nextElement();
                if (!ni.isLoopback()) {
                    Enumeration addressEnumeration = ni.getInetAddresses();

                    while(addressEnumeration.hasMoreElements()) {
                        InetAddress address = (InetAddress)addressEnumeration.nextElement();
                        if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && !address.isAnyLocalAddress()) {
                            return address;
                        }
                    }
                }
            }
        } catch (SocketException var4) {
            logger.warn("fail to get local ip." + var4.getMessage(), var4);
            return null;
        }

        logger.warn("No validated local address!");
        return null;
    }

    private static InetAddress getLocalAddress0() {
        InetAddress localAddress = null;

        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        } catch (Throwable var6) {
            logger.warn("Failed to retriving ip address, " + var6.getMessage(), var6);
        }

        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while(interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = (NetworkInterface)interfaces.nextElement();
                        Enumeration<InetAddress> addresses = network.getInetAddresses();
                        if (addresses != null) {
                            while(addresses.hasMoreElements()) {
                                try {
                                    InetAddress address = (InetAddress)addresses.nextElement();
                                    if (isValidAddress(address)) {
                                        return address;
                                    }
                                } catch (Throwable var5) {
                                    logger.warn("Failed to retriving ip address, " + var5.getMessage(), var5);
                                }
                            }
                        }
                    } catch (Throwable var7) {
                        logger.warn("Failed to retriving ip address, " + var7.getMessage(), var7);
                    }
                }
            }
        } catch (Throwable var8) {
            logger.warn("Failed to retriving ip address, " + var8.getMessage(), var8);
        }

        logger.error("Could not get local host ip address, will use 127.0.0.1 instead.");
        return localAddress;
    }

    public static String getHostName(String address) {
        try {
            int i = address.indexOf(58);
            if (i > -1) {
                address = address.substring(0, i);
            }

            InetAddress inetAddress = InetAddress.getByName(address);
            if (inetAddress != null) {
                return inetAddress.getHostName();
            }
        } catch (Throwable var3) {
        }

        return address;
    }

    public static String getIpByHost(String hostName) {
        try {
            return InetAddress.getByName(hostName).getHostAddress();
        } catch (UnknownHostException var2) {
            return hostName;
        }
    }

    public static String toAddressString(InetSocketAddress address) {
        return address.getAddress().getHostAddress() + ":" + address.getPort();
    }

    public static InetSocketAddress toAddress(String address) {
        int i = address.indexOf(58);
        String host;
        int port;
        if (i > -1) {
            host = address.substring(0, i);
            port = Integer.parseInt(address.substring(i + 1));
        } else {
            host = address;
            port = 0;
        }

        return new InetSocketAddress(host, port);
    }
}
